package com.maomao.controller;

import com.maomao.excel.ExcelData;
import com.maomao.excel.WriteExcelUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author xiaomin
 * @date 2018/4/11
 */
@Controller
@RequestMapping("/excel")
public class ExcelController {

    @ResponseBody
    @RequestMapping("/{text}")
    public void createExcel(@PathVariable String text, HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 告诉浏览器用什么软件可以打开此文件
//        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setContentType("application/vnd.ms-excel");
        // 下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode("text.xlsx", "utf-8"));
        ExcelData excelData=new ExcelData();
        excelData.setName("text");
        List<String> listTitles=new ArrayList<>();
        listTitles.add("a");
        listTitles.add("b");
        excelData.setTitles(listTitles);
        List<Object> listRow=new ArrayList<>();
        List<List<Object>> listRows=new ArrayList<>();
        listRow.add("1");
        listRow.add("2");
        listRows.add(listRow);
        excelData.setRows(listRows);
        WriteExcelUtil.exportExcel(excelData,response.getOutputStream());

    }
}
